<template>
  <view 
    :class="['audio-message', isPlaying ? 'is-playing' : '', isMine ? 'my-audio' : '']" 
    @click.stop="handlePlayAudioMessage"
    :style="{ width: calculateWidth() }"
  >
    <!-- 播放状态显示波形，否则显示静态图标 -->
    <view v-if="isPlaying" class="waveform-container">
      <view class="waveform">
        <view class="wave-bar" :style="{ animationDelay: '-0.8s' }"></view>
        <view class="wave-bar" :style="{ animationDelay: '-0.7s' }"></view>
        <view class="wave-bar" :style="{ animationDelay: '-0.6s' }"></view>
        <view class="wave-bar" :style="{ animationDelay: '-0.5s' }"></view>
        <view class="wave-bar" :style="{ animationDelay: '-0.4s' }"></view>
      </view>
    </view>
    <image v-else class="audio-icon" src="@/static/timstatic/images/audio-msg.png" mode=""></image>
    
    <!-- 时长始终显示 -->
    <view class="audio-duration">
      {{ message.payload.second + '″' }}
    </view>
  </view>
</template>

<script>
// 脚本逻辑保持不变
export default {
  data() {
    return {
      audio: null,
      isPlaying: false
    };
  },
  props: {
    message: {
      type: Object,
      default: () => ({})
    },
    isMine: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    calculateWidth() {
      const seconds = this.message?.payload?.second || 0;
      const baseWidth = 150;
      const additionalWidth = Math.floor(seconds / 5) * 10;
      const totalWidth = baseWidth + additionalWidth;
      const maxWidth = 500;
      return `${Math.min(totalWidth, maxWidth)}rpx`;
    },
    handlePlayAudioMessage() {
      if (!this.message?.payload?.url) {
        uni.showToast({ icon: 'none', title: '音频地址不存在' });
        return;
      }
      if (this.isPlaying) {
        this.audio.stop();
        this.isPlaying = false;
      } else {
        uni.$emit('stopOtherAudios');
        this.audio.src = this.message.payload.url;
        this.audio.play();
      }
    }
  },
  watch: {
    message: {
      handler(newVal) {
        this.message = newVal;
      },
      immediate: true,
      deep: true
    }
  },
  beforeMount() {
    this.audio = uni.createInnerAudioContext();
    this.audio.obeyMuteSwitch = false;
    this.audio.onPlay(() => this.isPlaying = true);
    this.audio.onEnded(() => this.isPlaying = false);
    this.audio.onError(() => {
      this.isPlaying = false;
      uni.showToast({ icon: 'none', title: '播放失败' });
    });
  },
  beforeUnmount() {
    this.audio?.stop();
    this.audio?.destroy();
  },
  created() {
    uni.$on('stopOtherAudios', () => {
      if (this.isPlaying) {
        this.audio.stop();
        this.isPlaying = false;
      }
    });
  },
  beforeDestroy() {
    uni.$off('stopOtherAudios');
  }
};
</script>

<style>
	@import './index.css';
</style>